package org.nahtanoj.contacts;

import java.util.ArrayList;
import java.util.List;

import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactGroupEntry;
import com.google.gdata.data.extensions.Name;

public class ContactGroup {
	private final List<ContactEntry> contacts = new ArrayList<ContactEntry>();
	private ContactGroupEntry group;

	public ContactGroup(ContactGroupEntry groupEntry) {
		this.group = groupEntry;
	}

	public void addContact(ContactEntry contactEntry) {
		this.contacts.add(contactEntry);
	}

	public List<ContactEntry> getContacts() {
		return contacts;
	}

	public ContactGroupEntry getGroup() {
		return group;
	}

	// Returns a list of candidate contacts that match the supplied details
	public List<ContactEntry> matchContact(Contact c) {
		List<ContactEntry> m = new ArrayList<ContactEntry>();
		for (ContactEntry e : this.contacts) {
			if (c.getFirstName().equals(e.getName().getGivenName().getValue())
					&& (c.getLastName().equals(e.getName().getFamilyName().getValue()))) {
				m.add(e);
			}
		}
		return m;
	}

	public void setGroup(ContactGroupEntry contactGroupEntry) {
		this.group = contactGroupEntry;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append(this.group.getTitle().getPlainText());
		sb.append(":");
		sb.append(this.contacts.size());
		sb.append("\n");
		for (ContactEntry entry : this.contacts) {
			if (entry.hasName()) {
				Name name = entry.getName();
				if (name.hasFullName()) {
					String fullNameToDisplay = name.getFullName().getValue();
					if (name.getFullName().hasYomi()) {
						fullNameToDisplay += " ("
								+ name.getFullName().getYomi() + ")";
					}
					sb.append("\t\t" + fullNameToDisplay);
				} else {
					sb.append("\t\t (no full name found)");
				}
				sb.append("\n");
			}

		}
		return sb.toString();
	}
}
